#include <nxos.h>
#include <winbuf/winbuf.h>

#if CONFIG_WINBUF_TEST == 1

NX_IMPORT void WinbufTest(void);

NX_Error NX_Main(char *cmdline, char *envline)
{
    WinbufTest();
    return NX_EOK;
}
#else 

NX_PRIVATE NX_U32 WinbufThread(void * arg)
{
    NX_Printf("winbuf thread startted\n");
    WinbufLoop();
    return 0;
}

/* no test, as server */
NX_Error NX_Main(char *cmdline, char *envline)
{
    NX_Error err;
    NX_U32 tid = 0;
    NX_Solt threadHandle = NX_SOLT_INVALID_VALUE;

    NX_Printf("INIT winbuf\n");

    /* init winbuf */
    if ((err = WinbufInit()) != NX_EOK)
    {
        NX_Printf("init win buf failed with %s!\n", NX_ErrorToString(err));
        return err;
    }
    NX_Printf("INIT winbuf done\n");
    
    if ((threadHandle = NX_ThreadCreate(NX_NULL, WinbufThread, NX_NULL, 0)) < 0)
    {
        err = NX_ErrorGet();
        NX_Printf("create win buf thread failed with %s!\n", NX_ErrorToString(err));
        return err;
    }

    NX_Printf("winbuf readt run udriver\n");
    
    /* init winbuf udriver */
    err = WinbufRunUdriver();
    NX_Printf("winbuf run udriver failed with %s!\n", NX_ErrorToString(err));
    
    /* kill winbuf thread before exit */
    tid = NX_ThreadGetId(threadHandle);

    NX_SignalSend(tid, NX_SIGNAL_KILL, NX_NULL);

    NX_Printf("winbuf server & driver exit with some reason.\n");

    return NX_EOK;
}
#endif
